'Copyright 2006 James Downey

Imports FetchXML
Imports FetchXMLBuilder.MetadataServiceSdk
Imports System.Configuration

Public Class frmFetchMetadata

    Private MainForm As frmMain

    Public Sub New(ByVal Form As frmMain)
        InitializeComponent()
        Me.MainForm = Form
    End Sub

    Public Function GetCRMServer() As String
        Try
            Dim url As String
            url = System.Configuration.ConfigurationManager.AppSettings("CRMServer")
            If url Is Nothing Then
                Return "http://localhost"
            Else
                Return url
            End If
        Catch exc As Exception
            Diagnostics.Debug.WriteLine(exc.Message)
            Return "http://localhost"
        End Try
    End Function

    Public Sub SetCRMServer(ByVal CRMServer As String)
        Try
            Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
            config.AppSettings.Settings.Clear()
            config.AppSettings.Settings.Add("CRMServer", CRMServer)
            config.Save(ConfigurationSaveMode.Modified)
            ConfigurationManager.RefreshSection("appSettings")
        Catch exc As Exception
            Debug.Print(exc.Message)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub btnFetch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFetch.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim url As String
            url = Me.txtCRMServer.Text
            If url.Length = 0 Then Throw New ApplicationException("Requires a url.")
            If Not url.Chars(url.Length - 1) = "/" Then url &= "/"
            MainForm.CrmServiceURL = url & "mscrmservices/2006/crmservice.asmx"
            url &= "mscrmservices/2006/metadataservice.asmx"
            Dim service As New MetadataService()
            If Me.chkCredentials.Checked Then
                Helpers.cred = System.Net.CredentialCache.DefaultCredentials
            Else
                Helpers.cred = New Net.NetworkCredential(txtUser.Text, txtPassword.Text, txtDomain.Text)
            End If
            service.Credentials = Helpers.cred
            service.Url = url
            Dim metadata As Metadata
            SetCRMServer(Me.txtCRMServer.Text)
            metadata = service.RetrieveMetadata(MetadataFlags.All)
            MainForm.SetMetadata(metadata)
            Me.DialogResult = Windows.Forms.DialogResult.OK
            Me.Cursor = Cursors.Default
        Catch exc As Exception
            Me.DialogResult = Windows.Forms.DialogResult.Retry
            Me.Cursor = Cursors.Default
            Windows.Forms.MessageBox.Show("Failed to retrieve metadata. Check that the url is correct and that you have the necessary permission. Error Message: " & exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub frmFetchMetadata_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.txtCRMServer.Text = GetCRMServer()
    End Sub

    Private Sub chkCredentials_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkCredentials.CheckedChanged
        Me.txtUser.Enabled = Not Me.chkCredentials.Checked
        Me.txtPassword.Enabled = Not Me.chkCredentials.Checked
        Me.txtDomain.Enabled = Not Me.chkCredentials.Checked
    End Sub

End Class